package cn.geracomium.action;

import cn.geracomium.util.action.AbstractAction;
import cn.geracomium.util.web.Page;
import cn.geracomium.util.web.StringKit;
import cn.gov.service.IAuthService;
import cn.gov.vo.Role;
import com.alibaba.dubbo.config.annotation.Reference;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by {wang jian} on 2018/06/26.
 */
@Controller
@RequestMapping("/pages/role/")
public class RoleAction extends AbstractAction {

    @Reference
    private IAuthService authService;

    @RequiresPermissions("role:list")
    @RequestMapping("listRoles")
    public ModelAndView listRoles() {
        ModelAndView mav = new ModelAndView("pages/files/role/role_list");
        String pageIndex = getRequest().getParameter("page");
        Integer pageNumber = StringKit.notBlank(pageIndex) ? Integer.valueOf(pageIndex) : 1;
        Map<String, Object> conditionMap = new HashMap<>();
        conditionMap.put("roleName", getRequest().getParameter("roleName"));
        Page<Role> page = authService.roleList(conditionMap, pageNumber);
        mav.addObject("roleResult", page);
        return mav;
    }

    @RequiresPermissions("role:delete")
    @RequestMapping("delRole")
    @ResponseBody
    public Integer delRole(Role role) {
        return authService.delRole(role.getRoleId());
    }

    @RequiresPermissions("role:add")
    @RequestMapping("addRole")
    public ModelAndView addRole() {
        ModelAndView mav = new ModelAndView("pages/files/role/role_add");
        mav.addAllObjects(authService.listByPersonalRole(getAccountId()));
        return mav;
    }

    @RequiresPermissions("role:add")
    @RequestMapping("editRole")
    @ResponseBody
    public boolean editRole(String optionId, String roleName, String roleDesc, String[] actions) {
        ArrayList<cn.gov.vo.RoleAction> list = new ArrayList<>();
        Role role = new Role();
        role.setOptionId(optionId);
        role.setRoleName(roleName);
        role.setRoleDesc(roleDesc);
        role.setLastUpdateUserId(getAccountId());
        for (String action : actions) {
            cn.gov.vo.RoleAction roleAction = new cn.gov.vo.RoleAction();
            roleAction.setAction(action.substring(1, action.length() - 1).replace("\"", ""));
            roleAction.setOptionId(optionId);
            list.add(roleAction);
        }
        return this.authService.addRole(role, list);
    }
}
